//
//  ZJFSecondViewController.m
//  OurTourism
//
//  Created by 张金峰 on 15/11/26.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//
#define CWIDTH self.view.frame.size.width
#define CHEIGHT self.view.frame.size.height
#import "ZJFSecondViewController.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"
#import "MZNetHandle.h"
#import "ZJFSecondCollectionViewCell.h"
#import "ZJFSecondHeaderCollectionReusableView.h"
#import "ZJFThiredViewController.h"
@interface ZJFSecondViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *modelNiceGuideArr;
@property (nonatomic, retain)UIImageView *backImg; //背景图片
@property (nonatomic, retain)UIButton *btn;
@property (nonatomic, copy)NSString *url;
@property (nonatomic, retain)UIView *navi;
@property (nonatomic, retain)ZJFguiDeModel *guidemodel;

@property (nonatomic, retain)ZJFSecondHeaderCollectionReusableView *header;

@end

@implementation ZJFSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self createView];
    [self navialpha];
    [self loadMBProgress];
    [self getData];
}
- (void)navialpha
{
    self.navi = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    self.navi.alpha = 0;
    [self.view addSubview:self.navi];
    //self.navi.backgroundColor = [UIColor blueColor];
   self.navi.backgroundColor =  [UIColor colorWithRed:62 / 255. green:176 / 255. blue:192 / 255. alpha:1];
    //创建返回按钮
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.btn];
    [self.btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).offset(30);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    self.btn.backgroundColor = [UIColor orangeColor];
    [self.btn setImage:[UIImage imageNamed:@"leftBack"] forState:UIControlStateNormal];
    [self.btn addTarget:self action:@selector(backToLast) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)getData
{
    NSString *url1 = [NSString stringWithFormat:@"http://app6.117go.com/demo27/php/discoverAction.php?start=&length=12&submit=localityHome6_2&locid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=144629fa99d7f149d9082d1f6a747eff", self.itemid];
    
    [MZNetHandle getUrl:url1 cookie:nil result:^(id result) {
        self.guidemodel = [[ZJFguiDeModel alloc]init];
        [ self.guidemodel setValuesForKeysWithDictionary: result[@"obj"][@"head"][@"locality"]];
     //   NSLog(@"1111111111111111111111111111111111%@222222%@",self.guidemodel.picdomain,self.guidemodel.picfile);
        [self getDataTwo];
    }];
    
    
}

- (void)getDataTwo
{
    
    NSString *url2 = [NSString stringWithFormat:@"http://app6.117go.com/demo27/php/discoverAction.php?start=&subtype=-1&length=12&submit=getLocalityTours&locid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=1352e105ccabb70fee0447c786660da0", self.itemid];
    [MZNetHandle getUrl:url2 cookie:nil result:^(id result) {
        if (result[@"obj"][@"tags"] != nil) {
            
            self.modelNiceGuideArr = [NSMutableArray array];
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSMutableDictionary *dic in result[@"obj"][@"list"]) {
                [tempArr addObject:dic];
            }
            self.modelNiceGuideArr = [ZJFguiDeModel transformWithArray:tempArr];
        }
        self.url = [NSString stringWithFormat:@"%@%@%@",self.guidemodel.picdomain,@"upload/",self.guidemodel.picfile];
        [self.collectionView reloadData];
        [self.hud removeFromSuperview];
    }];
    
}
#pragma mark - 创建collectionView
- (void)createView
{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((CWIDTH - 30) / 2, (CWIDTH - 30)/ 2 + 110);
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 70);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) collectionViewLayout:layout];
    self.collectionView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
    
    // self.collectionView.backgroundColor = [UIColor colorWithRed:0.98 green:0.95 blue:0.9 alpha:1];
    self.collectionView.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[ZJFSecondCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self.collectionView registerClass:[ZJFSecondHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    
    self.backImg = [[UIImageView alloc] init];

}

#pragma mark - colloction 协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZJFSecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.cornerRadius = 6;
    cell.layer.masksToBounds = YES;
    cell.guideModel = self.modelNiceGuideArr[indexPath.item];
    return cell;
}

#pragma mark - item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelNiceGuideArr.count;
    return 10;
}

#pragma mark - 背景图下滑改变宽高
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   // CGFloat yOffset1  = self.collectionView.contentOffset.y ;
  //  NSLog(@"%lf",yOffset1);
    
    if (self.collectionView.contentOffset.y <= 0 && self.collectionView.contentOffset.y >= -64) {
        self.navi.alpha = (64 + self.collectionView.contentOffset.y) / 64;
    }
    else if (self.collectionView.contentOffset.y > 0)
    {
        self.navi.alpha = 1.0;
    }
    else
    {
        self.navi.alpha = 0.0;
    }
    
    //获取当前偏移量
    CGFloat yOffset  = scrollView.contentOffset.y ;
    if (yOffset < -250) {
        CGRect f = self.backImg.frame;
        f.origin.y = yOffset ;
        f.size.height =  -yOffset ;
        self.backImg.frame = f;
        
    }
    if (scrollView.contentOffset.y <= 0 && scrollView.contentOffset.y >= -64) {
        self.navigationController.navigationBar.alpha = (64 + scrollView.contentOffset.y) / 64;
    }
    else if (scrollView.contentOffset.y > 0)
    {
        self.navigationController.navigationBar.alpha = 1.0;
    }
    else
    {
        self.navigationController.navigationBar.alpha = 0.0;
    }
    
}
#pragma mark - 视图要消失时候 设置bar出现
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark - 视图要出现时候 隐藏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
#pragma mark - 按钮触发方法
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - collectionView的头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        
        ZJFSecondHeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        
        self.backImg.backgroundColor = [UIColor redColor];
        [headerView addSubview:self.backImg];
        [self.backImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerView.mas_top).offset(-200);
            make.left.mas_equalTo(headerView.mas_left).offset(0);
            make.size.mas_equalTo(CGSizeMake(headerView.frame.size.width, 200));
        }];
        [self.backImg sd_setImageWithURL:[NSURL URLWithString:self.url] placeholderImage:[UIImage imageNamed:@"city"]];
        self.backImg.contentMode = UIViewContentModeScaleAspectFill;//设置img高度改变时 宽度也改变
        //裁剪
        self.backImg.clipsToBounds = YES;
        self.backImg.userInteractionEnabled = YES;
        return headerView;
    }
    else
    {
        return nil;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZJFThiredViewController *thirdDetail = [[ZJFThiredViewController alloc]init];

   thirdDetail.listID = [self.modelNiceGuideArr[indexPath.row] listId];
  //  NSLog(@"%@",thirdDetail.listID);
    thirdDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:thirdDetail animated:YES];

}

//#pragma mark-滑动手势1
//- (void)addScreenEdgePan
//{
//    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
//    screenEdgePan.edges = UIRectEdgeLeft;
//    [self.view addGestureRecognizer:screenEdgePan];
//    [self.collectionView addGestureRecognizer:screenEdgePan];
//    [screenEdgePan release];
//}
//#pragma mark-滑动手势2
//-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}


- (void)loadMBProgress
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    
    self.hud.dimBackground = NO;
    //设置对话框文字
    self.hud.labelText = @"loading";
    self.hud.minShowTime = 50;
    self.hud.activityIndicatorColor = [UIColor whiteColor];
    self.hud.labelColor = [UIColor whiteColor];
    
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1);
    } completionBlock:^{
        //操作执行完后取消对话框
        [self.hud removeFromSuperview];
        self.hud = nil;
    }];
    
}

//计算文本高度的方法
+ (CGFloat)heightWithText:(NSString *)text fontSize:(CGFloat)fontsize Width:(CGFloat)width

{
    //设置一个字典 保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]};
    
    //预设尺寸 文本最大不会超过这个范围
    CGSize size = CGSizeMake(width, 2000);
    //根据文本信息 计算得到一个CGRect
    //参数1. 尺寸范围
    //参数2. 获取文本尺寸的方式
    //参数3. 文本属性
    //参数4. 无用信息(上下文)
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
